package com.atguigu.windows;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class Flink11_Sideout2 {
    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
        env.setParallelism(2);

        DataStreamSource<String> ds = env.socketTextStream("hadoop162", 9999);
        SingleOutputStreamOperator<String> stream = ds.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] datas = value.split(",");
                return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
            }
        }).process(new ProcessFunction<WaterSensor, String>() {
            @Override
            public void processElement(WaterSensor value,
                                       Context ctx,
                                       Collector<String> out) throws Exception {
                //对数据进行处理
                if (value.getId().equals("sensor1")) {
                    //放入主流
                    out.collect(value.toString());
                } else if (value.getId().equals("sensor2")) {
                    ctx.output(new OutputTag<String>("s2") {
                    }, value.toString());
                }
            }
        });

        stream.print();
        stream.getSideOutput(new OutputTag<String>("s2"){}).print("s2");


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
